package com.sky.config;

import com.sky.properties.OkHttpProperties;
import com.sky.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class OkHttpConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public OkHttpUtil okHttpClient(OkHttpProperties properties) {
        log.info("开始创建OkHttpClient:{}", properties);
        OkHttpClient.Builder builder = new OkHttpClient.Builder().callTimeout(properties.getConnectTimeout(), TimeUnit.SECONDS).connectTimeout(properties.getConnectTimeout(), TimeUnit.SECONDS) // 设置连接超时时间
                .readTimeout(properties.getReadTimeout(), TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(properties.getWriteTimeout(), TimeUnit.SECONDS) // 设置写入超时时间
                .retryOnConnectionFailure(false) // 是否自动重试连接失败的请求
                .connectionPool(new ConnectionPool(properties.getMaxConnect(), properties.getKeepAlive(), TimeUnit.MINUTES)); // 设置连接池;
        return new OkHttpUtil(builder.build());
    }
}
